from django.contrib.auth.backends import ModelBackend
from user.models import User
import re



# 重写方法指定返回结果
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username': user.username,
        'user_id': user.id
    }


class MobileNameView(ModelBackend):
    # 重写用户名验证
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 判断username的数据形式
        try:
            if re.match(r'1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)

        except:
            user = None

        # 密码校验
        if user is not None and user.check_password(password):
            print('用户登陆成功%s' % user)
            return user

        return user
